home *** CD-ROM | disk | FTP | other *** search
- Path: EU.net!sun4nl!xs4all!usenet
- From: martijnl@xs4all.nl (Martijn Lievaart)
- Newsgroups: comp.lang.c++
- Subject: Re: Forward declarations: why won't they work?
- Date: Sun, 24 Mar 1996 10:37:38 GMT
- Organization: XS4ALL, networking for the masses
- Message-ID: <4j38ls$m96@news.xs4all.nl>
- References: <4ivpp0$iut@hustle.rahul.net>
- NNTP-Posting-Host: mas01-09.dial.xs4all.nl
- X-Newsreader: Forte Free Agent 1.0.82
-
- Theodore Sternberg <strnbrg@rahul.net> wrote:
-
- >Forward class declarations only seem to work sometimes. When they don't
- >work, I get a compiler error to the effect that "struct foo is an
- >imcomplete type". Can anyone tell me what's going on, i.e. when forward
- >class declarations are and are not possible?
-
- >Ted Sternberg
- >San Jose, California, USA
-
- A forward reference only tells the compiler 'there exists a class foo'
- but not what it looks like. You can use this to declare pointers and
- references to this class, but not use the class members or do anything
- where the compiler needs to now the size of the class. The error msg
- you get tells you the compiler needs the complete class declaration.
-
- Why use forward references?
- Sometimes you need to make circular references:
-
- class B;
-
- class A
- {
- B *b;
- //void cannot_do_this() { delete b; } // see below.
- };
-
- class B
- {
- A *a;
- }
-
- Here you need a forward reference because as A is declared B is still
- unknown.
-
- Note that if you 'delete a member of class B' (see cannot_do_this()),
- you still need the complete class declaration because the compiler
- needs to know the sizeof(B) and if it has a destructor.
-
- This can be solved by defining the member after class B has been
- declared, e.g:
- class B;
-
- class A
- {
- B *b;
- void can_do_this();
- };
-
- class B
- {
- A *a;
- }
-
- void A::can_do_this()
- {
- delete b;
- }
-
- Hope this clears things up,
- Martijn
- /~~~~~| /~~~~~| /~~~~~~|~~~~~\~~~~~\~~~~|~~~~~| We now return to our
- / |/ |/ | o | o | | +-| regularly scheduled
- / /| /| | /| | ___/ ___/ | +-| flame-throwing
- ../___/.|____/.|___|__/~|___|_|..|__|..|_____|_____|...martijnl@xs4all.nl..
-
-